Promise Chaining In Js

Posted on June 09, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Promise Chaining in js

Promises Chaining

Promises chaining is a technique used in JavaScript to handle asynchronous operations in a more readable and maintainable way. It allows you to write code that is easier to understand and debug, and it also helps to avoid the "callback hell" problem that can occur when dealing with multiple asynchronous operations. In this article, we will explore how to use promises chaining in JavaScript.

  • Allows multiple asynchronous operations to run in sequence.
  • Reduces callback hell by eliminating deeply nested functions.
  • Each then() returns a new promise, allowing further chaining.
  • Error handling is easier with a single .catch() for the entire chain.
  • Example:-

    function task(message, delay) {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log(message);
                resolve();
            }, delay);
        });
    }
    
    // Chaining promises
    task('Task 1 completed', 1000)
        .then(() => task('Task 2 completed', 2000))
        .then(() => task('Task 3 completed', 1000));

    Syntax of Promise Chaining

    asyncFunction()
      .then((result1) => {
        // Step 1 done
        return nextAsyncFunction(result1);
      })
      .then((result2) => {
        // Step 2 done
        return anotherAsyncFunction(result2);
      })
      .then((finalResult) => {
        // Final result
        console.log("Done:", finalResult);
      })
      .catch((error) => {
        // Handles any error in the chain
        console.log("Error:", error);
      });

    In this example, we have three asynchronous functions: `task1()`, `task2() `, and `task3()`. Each function returns a promise that resolves after a certain delay. We want to run these tasks in sequence, with each task starting only after the previous one has completed . We can use promise chaining to achieve this.

    Syntax of Promise Chaining

    asyncFunction()
      .then((result1) => {
        // Step 1 done
        return nextAsyncFunction(result1);
      })
      .then((result2) => {
        // Step 2 done
        return anotherAsyncFunction(result2);
      })
      .then((finalResult) => {
        // Final result
        console.log("Done:", finalResult);
      })
      .catch((error) => {
        // Handles any error in the chain
        console.log("Error:", error);
      });

    Example: Creating and Using a Promise

    In this example, we create a promise that resolves after a delay of 2 seconds. We wait for the promise to resolve and then log a message to the console. If an error occurs, we catch the error and log it to the console. We use the `then()` method to handle the resolved value and the `catch()` method to handle any errors that occur during the promise chain.

    function registerUser() {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(" User registered");
          resolve("User123");
        }, 1000);
      });
    }
    
    function sendWelcomeEmail(username) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(` Welcome email sent to ${username}`);
          resolve("Email sent");
        }, 1000);
      });
    }
    
    function logAction(status) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(" Action logged:", status);
          resolve("All done");
        }, 1000);
      });
    }

    Chaining the Promise

    registerUser()
      .then(sendWelcomeEmail)
      .then(logAction)
      .then((finalMessage) => {
        console.log("Final message:", finalMessage);
      })
      .catch((error) => {
        console.log(" Error occurred:", error);
      });;
    📢Important Note📢